import {ChangeDetectorRef, Component, ViewChild} from '@angular/core';
import {Content, IonicPage, NavController, NavParams, Select, ToastController} from 'ionic-angular';
import {ClientBirthdayProvider} from "../../../providers/client/client-brith/client-brith.provider";
import {ClientListItemModel} from "../../../model/pages/client/client-list/client-list-item.model";
import * as moment from "moment";
import {CallNumber} from "@ionic-native/call-number";
import {ClientNoteEditProvider} from "../../../providers/client/client-note/client-note-edit/client-note-edit.provider";
import {InfiniteScrollModel} from "../../../model/common/infinite-scroll.model";
import {MessageBushService} from "../../../services/common/message-bush.service";
import {SideMenuService} from "../../../services/common/side-menu.service";
import {TabsPage} from "../../tabs/tabs";
import {CallNumberService} from "../../../services/native/call-number/call-number.service";
import {LoadingService} from "../../../services/common/loading.service";
import {AdpActionSheetController} from "../../../components/common/adp-action-sheet/adp-action-sheet-controller";
import $ from 'jquery';

@IonicPage()
@Component({
    selector: 'page-client-birth',
    templateUrl: 'client-birth.html',
    providers: [
        CallNumber,
        ClientBirthdayProvider,
        ClientNoteEditProvider,
        SideMenuService,
        CallNumberService
    ]
})
export class ClientBirthPage extends InfiniteScrollModel {

    @ViewChild(Content) content: Content;
    clientsData: ClientListItemModel[];
    dataFilterType: number;
    //数据添加方式(0为替换，1为追加)
    addDataWay = 0;
    infiniteScroll = null;
    itemChangeOption = 90;
    dataTotal: string;
    isLoaded:boolean=false;
    get clientItemHeight(): string {
        const windowW = window['innerWidth'];
        return (windowW * 38.34 / 100) + 'px';
    }

    currentMobileList;
    currentMobile;
    currentClient;
    isScrolling = false;
    isViewDidLoad = false;
    isArriveBottom = false;
    @ViewChild('selectMobile') selectMobile: Select;
    $ionList;

    openRoot=(name, index)=>this.openTab(name, index);

    openMenu(myEvent){
        this.sideMenuService.openSideMenu(myEvent)
    }

    openTab(name, index){
        this.navCtrl.popToRoot();
        this.tabsPage.openPage({name:name, index:index});
    }

    constructor(public birthdayClientProvider: ClientBirthdayProvider,
                private callNumber: CallNumber,
                public navCtrl: NavController,
                public navParams: NavParams,
                private clientNoteEditProvider: ClientNoteEditProvider,
                public toastCtrl: ToastController,
                private sideMenuService:SideMenuService,
                public changeRef: ChangeDetectorRef,
                public tabsPage:TabsPage,
                private callNumberService: CallNumberService,
                private load: LoadingService,
                public adpActionSheetController:AdpActionSheetController,
                ) {
        super();
    }

    ionViewDidLoad() {
        this.isViewDidLoad = true;
        this.getBithClientListData(90, (p) => {
            if (p && p.error) {
                // this.mockData();
            }
        },0);

    }

    ionViewDidEnter() {
        const flag = MessageBushService.getMessage(MessageBushService.keys.birthdayClientListUpdated);
        if (flag == "1" && !this.isViewDidLoad) {
            this.ionViewDidLoad();
            MessageBushService.setMessage(MessageBushService.keys.birthdayClientListUpdated, "0");
        }
        this.isViewDidLoad = false;
        this.$ionList = $('.client-birth');
    }

    scrollStart(e) {
        this.isScrolling = true;
    }

    scrollEnd(e) {
        this.isScrolling = false;
    }

    scrolling(){
        const dimensions = this.content.getContentDimensions();
        if((!this.clientsData || this.clientsData.length==0) && this.isLoaded){
            return;
        }
        const temp1=dimensions.scrollHeight-dimensions.scrollTop-dimensions.contentHeight<100;
        if (temp1 !== this.isArriveBottom && this.$ionList.height() > dimensions.contentHeight) {
            this.isArriveBottom = temp1;
            this.changeRef.detectChanges();
        }
    }

    goUp() {
        if (this.isScrolling) {
            setTimeout(() => {
                this.goUp();
            }, 300);
            return;
        }
        this.content.scrollToTop();
    }

    /**
     * 获取生日客户列表数据
     * @param {number} type
     * @param {any} cb
     * @param {number} notLoading
     */
    getBithClientListData(type: number = 90, cb = null,notLoading) {
        this.isArriveBottom = false;
        this.dataFilterType = type;
        this.pageParams.pageSize = 0;
        if (notLoading !== 1) {
            this.load.showLoading();
        }
        this.birthdayClientProvider.getBirthdayList(type, 0, this.pageParams).subscribe(res => {
            if (res.total) {
                this.pageParams.pageSize = res.total;
                this.birthdayClientProvider.getBirthdayList(type, 1, this.pageParams).subscribe(res => {
                    this.pageInfo = res;
                    if(!res.list || !res.list.length){
                        this.dataTotal = '(0)';
                    }else{
                        this.dataTotal = `(${this.pageInfo.total})`;
                    }
                    const list = this.pageInfo.list;
                    list.forEach(client => {
                        if (client.deathFlag === 'Y') console.log(client.deathFlag, 'deathFlag = Y');
                        if (client.birthDate){

                            let subDays = client.passedDay;
                            let level = 'normal';
                            if (subDays < 8) {
                                level = 'urgent';
                            } else if (subDays >= 8 && subDays < 31) {
                                level = 'defer';
                            } else {
                                level = 'normal';
                            }
                            if (!isNaN(subDays)) {
                                let word = `${subDays}天后`;
                                if (subDays == 0) {
                                    word = `今天`;
                                } else if (subDays == 1) {
                                    // word = `明天生日`;
                                } else if (subDays == 2) {
                                    // word = `后天生日`;
                                }
                                client.birthdayDescribe = {
                                    level: level,//'urgent'、'defer'、'normal'
                                    value: word
                                };
                            }
                        }
                    });
                    if (this.addDataWay === 0) {
                        this.clientsData = list;
                        this.isLoaded = true;
                    } else {
                        this.clientsData = this.clientsData.concat(list);
                        this.isLoaded = true;
                    }
                    // this.clientsData = this.clientsData.filter(client => client.mobilePhone.length > 1);
                    //过滤为空的电话号码
                    this.clientsData = this.birthdayClientProvider.checkMobileNull(this.clientsData);
                    // console.log('---a----');
                    // console.log(this.clientsData);
                    this.isLoaded = true;
                    if (cb) cb();
                    this.load.dismissLoading();
                }, (code) => {
                    this.clientsData = [];
                    this.dataTotal = '(0)';
                    if (cb) cb({error: 1});
                    this.load.dismissLoading();
                });
            } else {
                this.clientsData = [];
                this.dataTotal = '(0)';
                if (cb) cb();
                this.load.dismissLoading();
            }

        },error2 => {
            if (cb) cb();
            this.load.dismissLoading();
        });
    }

    //到客户详情
    goToDetail(item) {
        this.navCtrl.push('HolderClientDetailPage', {
            clientNum: item.clientId,
            role:item.clientRole
        })
    }

    /**
     *  toast 提示信息
     * @param {string} message 提示内容
     * @param {string} position 显示位置
     */
    toast(message: string, position: string) {
        this.toastCtrl.create({
            message: message,
            position: 'middle',
            duration: 1200
        }).present();
    }

    /**
     * 后退
     */
    backHandle() {
        this.navCtrl.pop();
    }

    //调用原生打电话
    nativeCallPhone(mobilePhone?: string) {
        if (mobilePhone) {
            this.currentMobile = mobilePhone;
        }
        this.callNumberService.makeCall(this.currentMobile,
            this.callNumberService.initClientNoteLog(this.currentClient.clientId),
            true,
            this.callNumberService.initFollowStateLog(this.currentClient.clientId));
    }

    /**
     * 打电话
     */
    callClickHandle(item) {

        this.currentClient = item;
        this.currentMobileList = item.mobilePhone;
        if (!this.currentMobileList || this.currentMobileList.length < 1) return;
        if (this.currentMobileList.length === 1 && this.currentMobileList[0].mobile) {
            this.currentMobile = this.currentMobileList[0].mobile;
            this.nativeCallPhone();
            return;
        }else{
            const phoneArray = [];
            this.currentMobileList.forEach(phoneNumItem => {
                phoneArray.push({
                    text:phoneNumItem.mobile,
                    handler:() => {
                        this.currentMobile = phoneNumItem.mobile;
                        this.nativeCallPhone();
                    }
                });
            });
            this.adpActionSheetController.create({
                title:"选择电话",
                buttons:phoneArray
            }).present();
        }
    }

    itemChangeHandle(e) {
        this.pageParams.pageNum = 1;
        if (this.infiniteScroll) this.infiniteScroll.enable(true);
        this.addDataWay = 0;
        this.itemChangeOption = e.v;
        this.getBithClientListData(e.v, () => {
            this.goUp();
        }, 0);

    }

    /**
     * 格式化千分位
     * @param numP
     * @returns {string}
     */
    toThousands(numP) {
        let num = (numP || 0).toString(), result = '';
        while (num.length > 3) {
            result = ',' + num.slice(-3) + result;
            num = num.slice(0, num.length - 3);
        }
        if (num) {
            result = num + result;
        }
        return result;
    }

    /**
     * 下拉刷新
     */
    doRefresh(refresher) {
        if (this.infiniteScroll) this.infiniteScroll.enable(true);
        this.pageParams.pageNum = 1;
        this.addDataWay = 0;
        this.getBithClientListData(this.itemChangeOption, () => {
            refresher.complete();
        }, 1);
    }

}

